<template>
  <div class="login-content">
    <div class="logo-wrap">
      <img class="logo-img" src="../../../static/images/dangjian/login/logo2.png" alt="">
    </div>
    <div class="login-main flex-column flex-center">

      <div class="hd">
        <div class="lock"><img src="../../../static/images/dangjian/login/lock.png" alt=""></div>
      </div>

      <form class="login-form">
        <div v-if="ipAddressFlag">
        <input style="height: 50px;font-size: 30PX;color:red;" v-model="ipAddress" type="text" placeholder="后台地址">
        </div>
          <div class="mui-input-row flex-center login-put"  :class="{'inputActive':inputClass.name}">
          <div class="login-user-img"></div>
          <input v-on:focus="onfocus('name')" v-on:blur="onblur('name')" v-model="user.username" type="text" class="mui-input-clear" placeholder="请输入党员ID/手机号">
        </div>
        <div class="mui-input-row flex-center login-put last"  :class="{'inputActive':inputClass.password}">
          <div class="login-mima-img"></div>
          <input v-on:focus="onfocus('password')" v-on:blur="onblur('password')" v-model="user.password" v-if="!isShowPwd" type="password" class="mui-input-password" placeholder="请输入密码">
          <input v-on:focus="onfocus('password')" v-on:blur="onblur('password')" v-model="user.password" v-if="isShowPwd" type="text" class="mui-input-password" placeholder="请输入密码">
         <!-- <span class="mui-icon mui-icon-eye " @click="showPwd()" :class="{'mui-active':isShowPwd}"></span>-->
        </div>

        <div class="flex guest-login">
          <span @click="guestLogin">游客登录</span>
          <span v-if="false"><cube-checkbox v-model="forgetPwd">记住密码</cube-checkbox> </span>
          <span  @click.stop="findPwd" class="float-right">忘记密码</span>
        </div>
        <div v-if="false" @click="findPwd" class="more-info  ">
          <span class="color-tip">通过认证手机找回密码？</span>
          <span class="float-right">忘记密码</span>
        </div>


      </form>
    </div>
      <div @click="getToken()" class="default-btn">登&nbsp;&nbsp;录</div>
  </div>
</template>

<script>
  import loginService from '@/service/loginService'
  import tools from '@/utils/tools'
  import encrypt from '@/utils/encryptUtils'
  import version from '@/common/version'
  import StorageKeys from '@/common/const/StorageKeys'
  import apiRet from '@/common/config/api'
  export default {
    name: '',
    data () {
      return {
        isShowPwd: false,
        forgetPwd: true,
        user: {
          username: '',
          password: ''
        },/*
        user: {
          username: 'FQZFJDWGZ',
          password: '1'
        },*/
        isFocus: false,
        inputClass: {
          name: false,
          password: false
        },
        versionName: '',
        logoutFlag: '1',
        ipAddress:'', //测试地址
        type:'',//
        // ipAddressFlag:true //是否自定义地址 true 测试 false 关闭
        ipAddressFlag:false //是否自定义地址 true 测试 false 关闭
      }
    },
    mounted () {
      window['setDeviceID'] = (v) => {
        this.$localStorage.set('deviceIdIOS',v)
      }
    },
    created () {
      this.type = this.$route.params.type || ''; //如果为找回密码跳转过来的 则需要清空输入框
      // this.emptyPassword();
      if (Date.now() - localStorage.doubleUserLoginTime < 1000) {
        tools.alert('该账号已在其他设备登录,你已被迫下线')
      }
      this.$store.state.redFriendscircleNeedRefresh = true
      this.user.username = this.$localStorage.get('userNameCache')
      this.user.password = this.$localStorage.get('password')
      let flag = this.$localStorage.get('logoutFlag') || '1'
      console.log('--------------flag=', flag)
      this.logoutFlag = flag
      this.$localStorage.set('robotShow', 0)
      this.forgetPwd = this.$localStorage.get('forgetPwd')
      this.versionName = window.android && window.android.getVersionName()
      if (this.user.username && this.user.username !== '' && this.user.password && this.user.password !== '' && this.logoutFlag === '1') {
        this.getToken()
      }
    },
    methods: {
      /**
       * //清空密码
       */
      emptyPassword(){
        if(this.type ==='setPwd'){
          setTimeout(()=>{
            this.user.password = ''
          },500);
        }
      },
      onfocus (key) {
        this.isFocus = true
        this.inputClass[key] = true
      },
      onblur (key) {
        this.isFocus = true
        this.inputClass[key] = false
      },
      showPwd () {
        this.isShowPwd = !this.isShowPwd
      },
      findPwd () {
        // tools.alert('短信平台开始建设中')
        this.$router.push({name: 'findPwd'})
        // this.$router.push({path: `/setPwd/11220022`})
      },
      getMenus () {
        return loginService.getMenus().then((data)=>{
          if (data.code === 0) {
            let arrMenuKey = []
            if (data.menu.length>0) {
              data.menu[0].children.forEach((v, i) => {
                console.log(v, i)
                arrMenuKey.push(v.key)
              })
            }
            this.$localStorage.set('arrMenuKey', arrMenuKey)
          }
        })
      },
      guestLogin () {
        let data = {
          username: 'guest',
          password: 'Guest@2020#Zynnd'
        }
        loginService.token(data).then((res) => {
          console.log(res)
          if (res.code !== 0) {
            return this.tools.alert(res.message || res.resp_msg || '接口服务出错，请联系管理员')
          }
          window.myvue.$sessionStorage.set('token', res.data.access_token)
          this.userInfomation()
        })
      },
      async getToken() {
        if(this.user.username.toUpperCase() ==='**TEST**'){
          this.user.username = '';
          this.ipAddressFlag = true;
          return
        }
        if (this.ipAddressFlag && this.ipAddress && this.ipAddress != null && this.ipAddress != '' && typeof this.ipAddress != undefined) {
          await apiRet.testHost(this.ipAddress)
        }
        /*let rep = /^(?!(?:[^a-zA-Z]+|\\\\D+|[a-zA-Z0-9]+)$).{8,}$/g;
       if(!rep.test(this.user.password)){
          this.tools.tip('密码格式有误，请先修改密码',2000)
          return
        }*/
        let data = {
          password: this.user.password,
          username: this.user.username
        }
        this.$localStorage.set('forgetPwd', this.forgetPwd)
        this.$localStorage.set('password', this.user.password)
        console.log(data)
        this.tools.showLoading('登录中...')
        let timeout1 = setTimeout(() => {
          this.tools.hideLoading()
          this.tools.tip('网络超时，请重试',1000)
        }, 6000);
        loginService.token(data).then((res) => {
          clearTimeout(timeout1);
          this.tools.hideLoading()
          this.$store.state.userWarningFlag = true;//初始化首页是否弹出用户状态
          console.log(res)
          if (res.code !== 0) {
            return this.tools.alert(res.message || res.resp_msg || '哎呀，网络出错了')
          }
          window.myvue.$sessionStorage.set('token', res.data.access_token)
          this.$localStorage.set('userNameCache', this.user.username)
          this.clearCache()
          this.userInfomation()
          this.getCommonInfo(res.data.access_token)// 返回服务端公用配置信息
          this.$localStorage.set('logoutFlag', '1')
          this.$store.state.homeNeedRefresh = true
          this.keepToken(res.data.expires_in, res.data.access_token)
          if (window.android && window.android.h5CheckVersion) {
            window.android.h5CheckVersion(tools.getToken())
          }
        })
        // if (window.android && window.android.testJpush) {
        //   window.android.testJpush()
        // }
      },
      // 保持TOKEN有效
      keepToken (time, token) {
        let _time = (time - 30) * 1000
        if (_time < 0) {
          _time = time
        }
        clearTimeout(window.keepTokenTimer)
        window.keepTokenTimer = setTimeout(() => {
          this.fetchService.refreshToken({access_token: token}).then(res => {
            if (res.code === 0) {
              window.myvue.$sessionStorage.set('token', res.data.access_token)
              this.keepToken(res.data.expires_in, res.data.access_token)
            }
          })
        }, _time)
      },
      userInfomation () {
        this.fetchService.currentNew().then(res => {
          // if (res.code !== 0) {
          //   return tools.tip(res.message)
          // }
          this.$store.state.userInfo = res.data
          this.$localStorage.set('userInfo', res.data)
          this.loadPartyInfo(res.data.id)
          this.saveUserExamData(res.data.id)
          if (window.android && window.android.checkVersion) {
            window.android.checkVersion(version.version,encrypt.getUUID(6),tools.getToken(), 1)
          }
          if (window.android && window.android.setAliass) {
            window.android.setAliass(res.data.id)
          }
          this.$router.push({name:'home'})
        })
      },
      saveUserExamData (loginId) {
        let data = {
          loginId: loginId
        }
        this.fetchService.saveUserExamData(data).then(res => {
          // if (res.code !== 0) {
          //   return tools.tip(res.message)
          // }
        })
      },
      //获取党员信息
      loadPartyInfo (userId) {
        return this.fetchService.partyInfo(userId).then(res => {
          if (res.code !== 0) {
            this.$localStorage.set('partyInfo', {})
            return tools.tip(res.message)
          }
          this.$localStorage.set('partyInfo', res.data)
        })
      },
      getCommonInfo(access_token){// 返回服务端公用配置信息
        return this.fetchService.getCommonInfo({access_token:access_token}).then(res => {
          if (res.code === 0) {
            this.$localStorage.set('appCommonInfo',res.data)
            console.log('res.datares.data=',res.data);
            //设置轮询时间 默认60s
            this.$localStorage.set('pollingTime', new Number(res.data.checkinterval)*1000 || 5000)
          }
        })
      },
      /*清除缓存*/
      clearCache () {
        console.log('清除缓存')
        // 首页缓存信息 banner缓存标识，视频缓存标识，红云联盟标识，清除后自动更新以上数据
        this.$store.commit('setBANNER_AND_VIDEO', '')
        this.$store.commit('setRED_CLOUD_UNION', '')
        sessionStorage.removeItem('nativeWindowOpenTime')  // 防止调用阅读积分
      },
      login () {
        let pwd = sha256_digest(this.user.password)
        let deviceId = 'dsafasdfasdfasdfasdf'
        if (window.android && window.android.getDeviceId) {
          deviceId = window.android.getDeviceId()
        }
        tools.showLoading('登录中...')
        let timeout1 = setTimeout(() => {
          this.tools.hideLoading()
          this.tools.tip('网络超时，请重试',1000)
        }, 6000);
        loginService.getToken(this.user.username, pwd, deviceId).then((res) => {
          clearTimeout(timeout1);
          tools.hideLoading()
          if (res.code === 0) {
            this.$store.state.userWarningFlag = true;//初始化首页是否弹出用户状态
            let token = res.token
            this.$sessionStorage.set('userPwd', pwd)
            this.$localStorage.set('userNameCache', this.user.username)
            this.$sessionStorage.set('token', res.token)
            this.$localStorage.set('roleType', res.data.roleType)
            this.$store.state.roleType = res.data.roleType
            loginService.getMyUserInfo(token).then((userinfo) => {
              if (userinfo.code === 0) {
                if (userinfo.data.partyMemberModel === null) {
                  return tools.tip('此用户信息不完整')
                }
                this.$localStorage.set('userInfo', userinfo.data)
                this.$store.state.userInfo = userinfo.data
                if (this.$store.state.lastPage) {
                  try {
//                    this.$router.replace({path: this.$store.state.lastPage})
                    tools.back()
                  } catch (e) {
                    this.$router.push({name: 'home'})
                  }
                  return false
                }
                this.$router.push({name: 'home'})
              } else {
                tools.tip(res.message)
              }
            })
          } else {
            this.$createDialog({
              type: 'alert',
              title: '温馨提示',
              content: res.message || '服务出错',
              // icon: 'cubeic-alert'
            }).show()
          }
        })
      }
    }
  }
</script>
<style scoped lang="scss">
  @import "@/common/stylus/moon.scss";

  .login-content {
    background: url("../../../static/images/dangjian/login/hd-bg.png") left top no-repeat;
    background-position: -30% -12%;
    background-color:#E0E0E0;
    background-size: 453px auto;
    overflow: auto;
    padding-bottom:80px;
  }
  .logo-wrap {
    padding-top: pxToRem(41px);
    text-align: center;
    img.logo-img {
      height:pxToRem(296px);
      width:pxToRem(368px);
    }
  }
  .login-main {
    display:block;
    width:auto;
    margin: pxToRem(20px);
    margin-top:0;
    background:rgba(255,255,255,1);
    box-shadow:0px 5px pxToRem(20px) 0px rgba(0,0,59,0.1);
    padding:0;
    border-radius:pxToRem(10px);
    padding-bottom:57px;
    .hd {
      height: pxToRem(118px);
      width:100%;
      position: relative;
      margin-bottom:pxToRem(80px);
      background:url('../../../static/images/dangjian/login/hd.png') no-repeat top left;
      background-size:100% auto;
      .lock {
        position:absolute;
        height:pxToRem(87px);
        width:pxToRem(75px);
        top:pxToRem(91px);
        left:50%;
        transform:translateX(-50%);
        img {
          @include fullImg();
        }
      }
    }
    .login-form {
      width:auto;
      margin:0 60px;
      .login-put {
        height:pxToRem(88px);
        padding: 0 pxToRem(30px);
        border-radius:pxToRem(120px);
        background:rgba(255,255,255,1);
        border:1PX solid rgba(200, 200, 200, 1);
        margin-bottom:60px;
        position:relative;
        &:first-child {
          margin-bottom: pxToRem(45px);
          margin-top:110px;
        }
        &:last-child,&.last {
          margin-bottom:pxToRem(20px);
        }
        input {
          font-size:$titleFontSize;
          font-family:dang;
          padding-left:0px;
          color:#272727;
          height:inherit;
          &::-webkit-input-placeholder {
            color:#C2C2C2;
          }
        }
        .login-user-img,.login-mima-img {
          display:inline-block;
          width:36px;
          height:36px;
          margin-right:30px;
          background-size:auto 100%;
        }
        .login-user-img {
          background-image: url("../../../static/images/dangjian/login/icon-person2.png");
        }
        .login-mima-img {
          background-image: url("../../../static/images/dangjian/login/icon-pwd2.png");
        }
      }
      .more-info {
        font-size: $titleFontSize;
        margin-top:pxToRem(0px);
      }
    }
  }
  .guest-login {
    font-size: $titleFontSize;
    font-weight:400;
    text-align: center;
    color:#262626;
    margin: pxToRem(0px) pxToRem(20px) pxToRem(20px);
  }
  .default-btn {
    font-size: $titleFontSize;
    text-align: center;
    margin: 0 pxToRem(105px);
    margin-top:35px;
    color:#fff;
    height:90px;
    line-height:90px;
    background:rgba(220,0,0,1);
    box-shadow:0px 2px 16px 0px rgba(32,21,18,0.41);
    border-radius:150px;
  }
</style>
